package cn.farm.farm.Service.CommonService;

import cn.farm.farm.Config.Common.CommonException.DefaultException;
import cn.farm.farm.Config.Common.CommonException.LoginException;
import cn.farm.farm.Entity.Common.User;
import cn.farm.farm.Mapper.CommonMapper.ModifyUserMapper;
import cn.farm.farm.Mapper.CommonMapper.UserMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

@Service
@Transactional
public class UserModifyService {
    private Logger logger= LoggerFactory.getLogger(this.getClass());
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ModifyUserMapper modifyUserMapper;
    public User modify(Integer userid, String name, String nickname, String email,
                        String postcode, String introduction) {
        try{
            modifyUserMapper.update(userid,name,nickname,email,postcode,introduction);
            User user = modifyUserMapper.getUser(userid);
            return user;
        }catch (Exception e){
            logger.error(e.getMessage(), e);
            // 所有编译期异常转换为运行期异常
            throw new LoginException("modify inner error:" + e.getMessage());
        }

    }

    public void modifyPassword(Integer userid, String password) {
        try {
            Integer i = modifyUserMapper.updateopassword(userid,password);
            if(i==0){
                throw new DefaultException("修改密码失败");
            }
            //相当于只更新一个或指定（不为null或者“”的字段）
        }catch (DefaultException e){
            throw new DefaultException("modifyPassword Error: "+e.getMessage());
        }
    }

    public void modifyPhone(Integer userid, String phone) {
        try {
            Integer i = modifyUserMapper.modifyPhone(userid,phone);
            if(i==0){
                throw new DefaultException("修改绑定电话失败");
            }
            //相当于只更新一个或指定（不为null或者“”的字段）
        }catch (DefaultException e){
            throw new DefaultException("modifyPassword Error: "+e.getMessage());
        }
    }

    public void ModifyPhoto(Integer userid,String photoPath) {

        Example example = new Example(User.class);
        example.createCriteria().andEqualTo("userid",userid);
        List<User> list = userMapper.selectByExample(example);

        User user = list.get(0);
        user.setPhoto(photoPath);
        try {
            Integer i = userMapper.updateByExample(user,example);
            if(i==0){
                throw new DefaultException("修改头像失败");
            }
        }catch (DefaultException e){
            throw new DefaultException("modifyPassword Error: "+e.getMessage());
        }
    }
}
